#资源页面升级操作
import os
import sys
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import threading
import ast

class PageOperator:
    def __init__(self, driver, village_urls):
        self.driver = driver
        self.village_urls = village_urls

    def check_and_upgrade_resources(self):
        try:
            for village_url in self.village_urls:
                self.driver.get(village_url)
                time.sleep(3)
                self._upgrade_resources_in_village()
        except Exception as e:
            print(f"在资源页面操作时发生错误：{e}")

    def _upgrade_resources_in_village(self):
        try:
            for resource_id in range(1, 19):
                element_xpath = f"//a[@href='/build.php?id={resource_id}']"
                element = self.driver.find_element(By.XPATH, element_xpath)
                class_value = element.get_attribute("class")
                # 检查class属性中是否包含'good'且不包含'maxLevel'或'notNow'
                if "good" in class_value and "maxLevel" not in class_value and "notNow" not in class_value:
                    print(f"资源 {resource_id} 可升级，class_value 包含 'good'")
                    self.driver.get(f"https://ts1.x1.asia.travian.com/build.php?id={resource_id}")
                    print("当前url", self.driver.current_url)
                    time.sleep(1)
                    resource_button = self.driver.find_element(By.CSS_SELECTOR, "button.textButtonV1.green.build")
                    resource_button.click()
                    time.sleep(2)
        except Exception as e:
            print(f"在升级资源时发生错误：{e}")